import { Body, Controller, Get, Post, Res, HttpStatus, UploadedFile, UseInterceptors, HttpException, Query,Request } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import e, { Response } from 'express';
import { Profit } from './profit.entity';
import { ProfitService } from './profit.service';
import { WxUserService } from '../wxUser/wxUser.service';
import { AnswerService } from '../answer/answer.service';
import {
  EnumProfitPostAnswer,
  profitEnum, profitTypeEnum
} from './profit.enum'
import {
  get,
  post
} from 'request'
import request from 'request'
import {join, resolve} from 'path'
import { createWriteStream } from 'fs';
import { ValidTokenInterceptor } from '../../interceptor/validToken'
import { ValidRSAInterceptor } from '../../interceptor/validRSA'
import utils from '../../common/utils'

import {
  existsSync,
  mkdirSync
} from 'fs'

import {
  apibefore
} from '../../router'
import { MultiImgService } from '../multiImg/multiImg.service';
import { Answer } from '../answer/answer.entity';
import { AnswerInfo } from '../answerInfo/answerInfo.entity';
import { AnswerInfoService } from '../answerInfo/answerInfo.service';
import { RedisInstance } from 'src/common/redis';
import ladderAlgorithm from 'src/common/ladderAlgorithm';
import ladderAlgorithmH5 from 'src/common/ladderAlgorithmH5';
import { system_wx_user, video_RefererKey, video_VideoTimeout } from 'src/setting';
import { TypeEnum } from '../answerReportErrors/answerReportErrors.enum';

@Controller(apibefore('/profit'))
@UseInterceptors(ValidTokenInterceptor)
export class ProfitController {
  constructor(private readonly service: ProfitService,
    private readonly answerService: AnswerService,
    private readonly wxuserService: WxUserService,
    private readonly mutImgService: MultiImgService,
    private readonly answerInfoService: AnswerInfoService) {}


  /**
   * 查询用户可提现的数额
   */
  @Get('findWithdrawal')
  @UseInterceptors(ValidRSAInterceptor)
  async findWithdrawal(@Request() req){
      return await this.service.findWithdrawal(req.headers.wx_user);
    }

  /**
   * 查询所有用户的收入
   * @param params
   * @param req
   * @returns
   */
  @Get('findAll_By_User')
  @UseInterceptors(ValidRSAInterceptor)
  findAll_By_User(@Query() params:{pageSize:number,pageIndex:number},@Request() req){
    let pageSize: number = Number(params.pageSize || 0)
    let pageIndex: number = Number(params.pageIndex || 0)
    let skip: number = pageSize * pageIndex
    return this.service.findAll_By_User(skip, pageSize, req.headers.wx_user)
  }

  /**
   * 查询某个作品的所有收入记录
   * @param params
   * @returns
   */
  @Get('findAll_By_Video')
  @UseInterceptors(ValidRSAInterceptor)
  findAll_By_Video(@Query() params:{pageSize:number,pageIndex:number,video_id:number}){
    let pageSize: number = Number(params.pageSize || 0)
    let pageIndex: number = Number(params.pageIndex || 0)
    let skip: number = pageSize * pageIndex
    return this.service.findAll_By_Video(skip, pageSize, params.video_id)
  }

  /**
   * 查询提现详情
   * @param params
   * @param req
   * @returns
   */
  @Get('findAll_By_Wallet')
  @UseInterceptors(ValidRSAInterceptor)
  async findAll_By_Wallet(@Query() params:{pageSize:number,pageIndex:number,wallet_flow_id:number},@Request() req){
    let wx_user = req.headers.wx_user
    let pageSize: number = Number(params.pageSize || 0)
    let pageIndex: number = Number(params.pageIndex || 0)
    let skip: number = pageSize * pageIndex
    return await this.service.findAll_By_Wallet(skip, pageSize, params.wallet_flow_id)
  }

  /**
   * 查询用户的收益（原创/非原创）
   * @param params
   * @param req
   * @returns
   */
  @Get('findAll_My_By_Original')
  @UseInterceptors(ValidRSAInterceptor)
  async findAll_My_By_Original(@Query() params:{pageSize:number,pageIndex:number,original:number},@Request() req){
    let wx_user = req.headers.wx_user
    let pageSize: number = Number(params.pageSize || 0)
    let pageIndex: number = Number(params.pageIndex || 0)
    let skip: number = pageSize * pageIndex
    let original = params.original
    if(original != 0 && original != 1){
      return new HttpException('参数传递错误', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return await this.service.findAll_My_By_Original(skip,pageSize,wx_user,original)
  }

  /**
   * 设置视频答案
   * @param wx_user
   * @param videoList
   */
   async setVideoAnswer(result: any){
    result.data.map(e => {
      let findAnswerResult = result.answerInfo.filter(c => c.answer_id === e.id)
      let answer = []
      let imgs = []
      findAnswerResult.map(async c => {
        answer.push(`${c.platform}:${c.ic_name}`)
        imgs.push(c.img)
      })
      e.answer = answer
      e.img = imgs
    })
  }

  setVideoAnswer_Wx_App(findAnswerResult: any, currentIsGroup: any){
    let e = {
      profit_result:'',
      profit_result_img:'',
      profit_result_img_avatar:'',
    }
    //自己回答审核通过，或者自己产生利润（返回答案）
    if(findAnswerResult.length > 0){
      let answer = []
      let imgs = []
      let img_ids = []
      let avatar_img = []
      let avatar_id = []
      findAnswerResult.map(async c => {
        answer.push(`${c.platform}:${c.ic_name}:${c.account||''}`)
        imgs.push(c.img)
        img_ids.push(c.img_id)
        avatar_img.push(c.avatar_img)
        avatar_id.push(c.avatar_id)
      })
      e.profit_result = answer.join(',')
      e.profit_result_img = imgs.join(',')
      e.profit_result_img_avatar = avatar_img.join(',')
    }
    if((e.profit_result || e.profit_result_img || e.profit_result_img_avatar) && currentIsGroup?.length > 0){
      //如果有关联的网红信息
      let answer = []
      let imgs = []
      let img_ids = []
      let avatar_img = []
      let avatar_id = []
      currentIsGroup.map(async c => {
        answer.push(`${c.platform}:${c.ic_name}:${c.account||''}`)
        imgs.push(c.img)
        img_ids.push(c.img_id)
        avatar_img.push(c.avatar_img)
        avatar_id.push(c.avatar_id)
      })
      e.profit_result = answer.join(',')
      e.profit_result_img = imgs.join(',')
      e.profit_result_img_avatar = avatar_img.join(',')
    }
    return e
  }

  /**
   * 退款
   * @param data 
   * @param req 
   */
  @Post('refund')
  @UseInterceptors(ValidRSAInterceptor)
  async refund(@Body() data,@Request() req){
    const wx_user = req.headers.wx_user
    const answer_id = data.answer_id

    let errorType = data.error_type
    if(errorType !== TypeEnum.people && errorType !== TypeEnum.people_update){
      return new HttpException('报错信息有误',HttpStatus.INTERNAL_SERVER_ERROR)
    }else{
      let err = await this.service.refund(wx_user, answer_id, errorType, data.platform, data.account, data.ic_name, data.avatar_id, data.avatar_img, data.img, data.img_id)
      if(err){
        return new HttpException(err,HttpStatus.INTERNAL_SERVER_ERROR)
      }else{
          const redis = RedisInstance.initRedis();
          redis.expire(utils.redis_payconsumption_key + wx_user,0)
          redis.quit()
      }
    }
  }

  /**
   * 获取防盗链视频链接
   * @param currentVideo
   */
  getPlayVideoUrl(currentVideo){
    let oldurl:any = currentVideo.video_url || ''
    let https = 'https://'
    let http = 'http://'
    if(oldurl.indexOf(https) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(https) + https.length)
    }else if(oldurl.indexOf(http) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(http) + http.length)
    }
    oldurl = oldurl.split('/')
    oldurl = oldurl.slice(1,oldurl.length - 1)
    let endTime:string = parseInt((new Date().getTime() / 1000 + video_VideoTimeout).toString()).toString(16)
    let sign = utils.md5(video_RefererKey + '/' + oldurl.join('/') + '/' + endTime)
    if(currentVideo.video_url){
      let newurl = currentVideo.video_url + '?t=' + endTime + '&sign=' + sign
      currentVideo.video_url = newurl
    }
  }

  /**
   * 设置视频答案
   * @param wx_user
   * @param videoList
   */
  async setVideoAnswer_List(wx_user: string, videoList: any, answerList: any, multiImg: any){
    videoList.map((e:any) => {
      let findAnswerList = answerList.filter(c => c.video_id == e.id)
      //视频审核通过的答案编号
      let findOKAnswher = findAnswerList.find(c => c.check == 1)
      e.check_answer = findOKAnswher?.answer_id
      //是否有驳回的答案
      if(!e.check_answer && findAnswerList.find(c => utils.judeAnswerIsReject(c))){
        e.check_answer = 0
      }
      //审核中的答案
      e.is_answer = findAnswerList.find(c => c.check != 1 && c.check !== 0 && c.wx_user == wx_user)?.wx_user
      //自己的所有答案
      e.is_answer_history = findAnswerList.find(c => c.wx_user == wx_user) ? true : false
      if(e.is_answer_history && e.original == 0 && findAnswerList.find(c => c.check == 1 && c.wx_user == e.video_author && c.wx_user == wx_user)){
        e.is_answer_history = false
      }
      //自己回答审核通过，或者自己产生利润（返回答案）
      let findAnswerResult = findAnswerList.filter(c => c.check == 1 && (c.wx_user == wx_user || (c.answer_id && c.use_wx_user == wx_user)))
      if(findAnswerResult.length > 0){
        e.is_profit_result = true
      }
      //自己回答审核通过，或者自己产生利润（返回多图）
      e.multi_img = multiImg.filter(c => c.video_id == e.id && ((c.check == 1 && c.wx_user == wx_user) || (c.answer_id && c.use_wx_user == wx_user)) && c.multi_img).map(c => c.multi_img)
      if(e.multi_img.length === 0){
        delete e.multi_img
      }
      e.multi_img_count = multiImg.filter(c => c.video_id == e.id).length

      let findProfit = findAnswerList.find(c => (c.check == 1 && c.wx_user == wx_user) || (c.answer_id && c.use_wx_user == wx_user))
      e.profit_works = findProfit?.id
      e.profit_status = findProfit?.profit_status
      if(e.video_author == wx_user){
        e.author = true
      }
      e.author_answer = findAnswerList.find(e => e.wx_user == wx_user) ? true : false
      if(e.video_author === system_wx_user){
        e.system_wx_user = true
      }
      delete e.video_author
    })
  }

  /**
   * 产生利润
   * @param data
   * @param req
   * @returns
   */
  @Post('create')
  @UseInterceptors(ValidRSAInterceptor)
  async create(@Body() data,@Request() req){
    //查询问题作者
    let answerUser = await this.answerService.findById(data.answer_id)
    if(!answerUser){
      return new HttpException('答案无效', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    const wx_user = req.headers.wx_user
    //查询当前用户是否存在
    let findUser = await this.wxuserService.findByWxUser(wx_user)
    if(!findUser){
      return new HttpException('当前用户未找到', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    let addData = new Profit()
    addData.answer_id = data.answer_id
    addData.use_wx_user = wx_user
    addData.author_wx_user = answerUser.wx_user
    addData.use_duration = data.use_duration
    addData.sum_duration = data.sum_duration
    addData.status = profitEnum.not_entry
    addData.create_time = new Date()
    try{

      if(data.lookType === 'ad'){
        if(data.platform === 'h5'){
          await ladderAlgorithmH5.set(wx_user)
        }else{
          await ladderAlgorithm.set(wx_user)
        }
      }else if(data.lookType === 'rewardIsAnswer'){
        //悬赏用户看答案
        addData.unit_price = 10
        addData.service_charge = 20
        addData.status = profitEnum.entry
        addData.type = profitTypeEnum.consume
        addData.update_time = new Date()
      }
      let addProfit:any = await this.service.create(addData)

      let answer:any = await this.answerService.find_answer_by_video_id(answerUser.wx_user, answerUser.video_id, [], data.loadType)
      let getAnswer:any = this.setVideoAnswer_Wx_App(answer.user_answer, answer.icGroup)

      //如果是多图作品 返回作品多图
      let mutimgs = await this.mutImgService.find_By_Video(answerUser.video_id)
      getAnswer.multi_img = mutimgs.map(e => e.img)
      getAnswer.profit_works = data.answer_id


        //根据地址获取防盗链地址 RefererKey
      answer.recommendList.map(currentVideo => {
        this.getPlayVideoUrl(currentVideo)
      })
      this.setVideoAnswer_List(wx_user, answer.recommendList, answer.answerInfo, answer.recommendMultiImg)

      
      return {answer: getAnswer, recommendList: answer.recommendList}
    }catch(err) {
      return new HttpException('产生利润失败，请重试', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  @Post('getLookType')
  @UseInterceptors(ValidRSAInterceptor)
  @UseInterceptors(ValidTokenInterceptor)
  async getLookType(@Request() req,@Body() data){
    let wx_user = req.headers.wx_user
    if(data.platform === 'h5'){
      return await ladderAlgorithmH5.get(wx_user)
    }else{
      return await ladderAlgorithm.get(wx_user)
    }
  }
}
